package com.cskaoyan.gateway.controller.user;

import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.IRegisterService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.KaptchaCodeRequest;
import com.mall.user.dto.KaptchaCodeResponse;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;



import java.util.HashMap;


@RestController
@RequestMapping("/user")
public class RegisterController {

    @Reference(timeout = 2000,  retries = 0, check = false)
    private IKaptchaService kaptchaService;


    @Reference(timeout = 2000, retries = 0, check = false)
    IRegisterService registerService;

    @Anoymous
    @PostMapping("/register")
    public ResponseData register(@RequestBody HashMap<String, String> map, HttpServletRequest request) {
        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        String email = map.get("email");
        String captcha = map.get("captcha");
        // 1. 判断验证码是否正确
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        kaptchaCodeRequest.setCode(captcha);
        kaptchaCodeRequest.setUuid(uuid);
        KaptchaCodeResponse kaptchaCodeResponse = kaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        if (!kaptchaCodeResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<>().setErrorMsg(kaptchaCodeResponse.getMsg());
        }

        // 2. 执行数据操作的具体业务
        UserRegisterRequest userRegisterRequest = new UserRegisterRequest();
        userRegisterRequest.setUserName(userName);
        userRegisterRequest.setUserPwd(userPwd);
        userRegisterRequest.setEmail(email);
        UserRegisterResponse userRegisterResponse = registerService.register(userRegisterRequest);
        if (userRegisterResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(null);
        }

        return  new ResponseUtil<>().setErrorMsg(userRegisterResponse.getMsg());
    }

}
